package com.bistu.openlab.uofspreadsheet.xmlparse;

import java.util.List;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.bistu.openlab.uofspreadsheet.model.DefaultHeightWidth;
import com.bistu.openlab.uofspreadsheet.model.ExcelSheetContent;
import com.bistu.openlab.uofspreadsheet.model.MaxRowCol;
import com.bistu.openlab.uofspreadsheet.model.SheetRow;

/*
 *@author xiaoguang.gao@oracle.com
 *@version 2013-5-9 
 */
public class ExcelSheetContentParse implements IXmlParse<ExcelSheetContent>{
	private static ExcelSheetContentParse parse = new ExcelSheetContentParse();
	public static ExcelSheetContentParse getInstance(){
		return parse;
	}
	private ExcelSheetContentParse(){}

	@Override
	public ExcelSheetContent readFromElement(Element root) {
		ExcelSheetContent sheetContent = null;
		if(root!=null&&root.getName().equals("工作表内容_E80E")){
			sheetContent = new ExcelSheetContent();
			//max row and column
			MaxRowColParse mrcParse = MaxRowColParse.getInstance();
			MaxRowCol mrc = mrcParse.readFromElement((Element)root.selectSingleNode("表:最大行列_E7E6"));
			sheetContent.setMaxRowCol(mrc);
			//default height and width
			DefaultHeightWidthParse dhwParse = DefaultHeightWidthParse.getInstance();
			DefaultHeightWidth dhw = dhwParse.readFromElement((Element)root.selectSingleNode("表:缺省行高列宽_E7E9"));
			sheetContent.setDefaultHW(dhw);
			//rows
			SheetRowParse rowParse = SheetRowParse.getInstance();
			List<Element> rowEleList = root.selectNodes("表:行_E7F1");
			if(rowEleList!=null&&rowEleList.size()>0){
				for(Element rowEle : rowEleList){
					sheetContent.addSheetRow(rowParse.readFromElement(rowEle));
				}
			}
		}
		return sheetContent;
	}

	@Override
	public Element writeToElement(ExcelSheetContent obj) {
		Element root = null;
		if(obj==null){
			obj = new ExcelSheetContent();
			obj.setDefaultHW(new DefaultHeightWidth());
			obj.setMaxRowCol(new MaxRowCol());
		}
		root = DocumentHelper.createElement("表:工作表内容_E80E");
		//max row and column
		MaxRowColParse mrcParse = MaxRowColParse.getInstance();
		Element mrcEle = mrcParse.writeToElement(obj.getMaxRowCol());
		if(mrcEle!=null)root.add(mrcEle);
		//default height and width
		DefaultHeightWidthParse dhwParse = DefaultHeightWidthParse.getInstance();
		Element dhwEle = dhwParse.writeToElement(obj.getDefaultHW());
		if(dhwEle!=null)root.add(dhwEle);
		//rows
		SheetRowParse rowParse = SheetRowParse.getInstance();
		if(obj.getRowList()!=null&&obj.getRowList().size()>0){
			for(SheetRow row : obj.getRowList()){
				Element rowEle = rowParse.writeToElement(row);
				if(rowEle!=null)
					root.add(rowEle);
			}
		}		
		return root;
	}

}
